<!-- 消息列表 -->
<template>
  <div id="mesageList">
    <!-- 详细信息 -->
    <template v-if="isShowMes">
      <div class="showMes">
        <!-- 消息标题 -->
        <div class="title">
          <div class="centent">
            <div class="tit">{{ state.currentMessageInfo.title }}</div>
            <div class="time" v-format-time>
              {{ state.currentMessageInfo.time }}
            </div>
          </div>
          <div class="more">
            <div class="prev" @click="backMesList">
              <i class="iconfont icon-ffanhui-"></i>
            </div>
            <div
              class="satrt"
              @click="changeStartMes(state.currentMessageInfo)"
            >
              <i
                class="iconfont icon-xingbiao"
                :class="state.currentMessageInfo.ifMark ? 'active' : ''"
              ></i>
            </div>
            <div class="delete" @click="delMes()">
              <i class="iconfont icon-shanchu"></i>
            </div>
          </div>
        </div>
        <!-- 消息内容 -->
        <div class="des">
          {{ state.currentMessageInfo.des }}
        </div>
      </div>
    </template>
    <!-- 信息列表 -->
    <template v-else>
      <div class="message">
        <template v-if="state.currentPageListData.length">
          <div class="meslist">
            <template v-for="item in state.currentPageListData" :key="item">
              <div class="mes">
                <!-- 收藏 -->
                <div
                  class="start"
                  tit="加入或移除星标"
                  @click="changeStartMes(item)"
                >
                  <i
                    class="iconfont icon-xingbiao"
                    :class="item.ifMark ? 'active' : ''"
                  ></i>
                </div>
                <!-- 未读提示 -->
                <!-- 星标 -->
                <template v-if="props.type === 3">
                  <template v-if="!item.ifStartRead">
                    <div class="pointer">
                      <i class="iconfont icon-weidu_biaoji"></i>
                    </div> </template
                ></template>
                <!-- 普通 -->
                <template v-else>
                  <template v-if="!item.ifRead">
                    <div class="pointer">
                      <i class="iconfont icon-weidu_biaoji"></i>
                    </div>
                  </template>
                </template>
                <!-- 消息标题 -->
                <a
                  href="javascript:void(0)"
                  class="tit"
                  @click="showMesInfo(item)"
                >
                  {{ item.title }}
                </a>
                <!-- 时间 -->
                <div class="time" v-format-time.relative>{{ item.time }}</div>
              </div>
            </template>
          </div>
          <!-- 分页 -->
          <div class="pagination">
            <!-- 上一页 -->
            <div class="pagePublic" @click="pageChangeSwitch(false)">
              <i class="iconfont icon-xiangzuo"></i>
            </div>
            <div class="pagelist">
              <div
                class="pageitem"
                v-for="item in state.pageNum"
                :key="item"
                :class="state.currentPageNum === item ? 'active' : ''"
                @click="showSwitchPageData(item)"
              >
                {{ item }}
              </div>
            </div>
            <!-- 下一页 -->
            <div class="pagePublic" @click="pageChangeSwitch()">
              <i class="iconfont icon-xiangyou1"></i>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="empty">
            <i class="iconfont icon-c-kongzhuangtai"></i>
            <span>暂无消息哦~</span>
          </div>
        </template>
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, defineProps } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import cache, { CacheType } from '@/utils/cache'
import {
  admintorDelMes,
  admintorStartMes,
  admintorReadMes,
  admintorCheck
} from '@/server/serve/api_admintor'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  UserInfoVuexTypes,
  UserInfoMessageListTypes
} from '@/server/serve/api_admintor'

interface PropsTypes {
  // 0 => 系统消息
  // 1 => 节日祝福,
  // 2 => 用于预约
  // 3 => 星标信息
  type: number
}
const props = defineProps<PropsTypes>()
const store = useStore()
const router = useRouter()

const state = reactive({
  // 分页数据
  pageListData: [] as Array<UserInfoMessageListTypes>,
  // 当前分页显示的数据
  currentPageListData: [] as Array<UserInfoMessageListTypes>,
  // 每页最大条数
  pageMaxskip: 10,
  // 分页数量
  pageNum: 0,
  // 当前分页页数
  currentPageNum: 1,
  // 当前点击的消息数据
  currentMessageInfo: {} as UserInfoMessageListTypes
})

// 是否显示具体的消息内容
const isShowMes = ref<boolean>(false)

// 获取用户数据
const userInfo = computed({
  get: () => store.state.userInfo as UserInfoVuexTypes,
  set: () => {}
})
// 监听vuex用户数据变化
watch(
  () => userInfo.value,
  (newVal) => {
    userInfo.value = newVal
    // 设置用户消息列表
    if (props.type === 3) {
      state.pageListData =
        userInfo.value.messageList?.filter(
          (item) => item.type === props.type
        ) ?? []
    } else {
      state.pageListData =
        userInfo.value.messageList?.filter(
          (item) => item.constType === props.type
        ) ?? []
    }
    //  当前分页显示的数据
    state.currentPageListData = state.pageListData.slice(0, state.pageMaxskip)
    //  设置分页数量
    state.pageNum = Math.ceil(state.pageListData.length / state.pageMaxskip)
  }
)
// 设置用户消息列表
if (props.type === 3) {
  state.pageListData =
    userInfo.value.messageList?.filter((item) => item.type === props.type) ?? []
} else {
  state.pageListData =
    userInfo.value.messageList?.filter(
      (item) => item.constType === props.type
    ) ?? []
}
//  当前分页显示的数据
state.currentPageListData = state.pageListData.slice(0, state.pageMaxskip)
//  设置分页数量
state.pageNum = Math.ceil(state.pageListData.length / state.pageMaxskip)

// 切换分页 展示数据
const showSwitchPageData = (num: number) => {
  state.currentPageNum = num
  state.currentPageListData = state.pageListData.slice(
    (num - 1) * state.pageMaxskip,
    (num - 1) * state.pageMaxskip + state.pageMaxskip
  )
}

// 展示具体内容
const showMesInfo = async (mesInfo: UserInfoMessageListTypes) => {
  isShowMes.value = true
  state.currentMessageInfo = mesInfo
  const mesIndex = userInfo.value.messageList.findIndex(
    (item) => item._id === state.currentMessageInfo._id
  )

  // 是否为星标阅读
  const ifStart = props.type === 3 ? true : false

  // 未读处理
  const { data } = await admintorReadMes(
    userInfo.value._id,
    mesInfo._id,
    mesIndex,
    ifStart
  )

  if (data.code)
    return ElMessage({
      type: 'warning',
      message: data.mes
    })
  // 本地处理 节约性能
  const newUserInfo = { ...userInfo.value }
  // 星标处理
  if (ifStart) {
    if (!mesInfo.ifStartRead) --newUserInfo.startUnread
    newUserInfo.messageList[mesIndex].ifStartRead = true
  }
  // 普通处理
  else {
    // 未读
    if (!mesInfo.ifRead) {
      switch (mesInfo.constType * 1) {
        case 0:
          --newUserInfo.systemUnread
          break
        case 1:
          --newUserInfo.festivalUnread
          break
        case 2:
          --newUserInfo.appointmentUnread
          break
      }
    }
    newUserInfo.messageList[mesIndex].ifRead = true
  }
  store.commit('setUserInfo', newUserInfo)
}

// 返回消息列表
const backMesList = () => {
  isShowMes.value = false
}

// 删除消息
const delMes = () => {
  ElMessageBox.confirm('确认删除该消息吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data } = await admintorDelMes(
        userInfo.value._id,
        state.currentMessageInfo._id
      )
      if (data.code)
        return ElMessage({
          type: 'warning',
          message: data.mes
        })
      ElMessage({
        type: 'success',
        message: data.mes
      })
      // 本地删除 节约性能
      const mesIndex = userInfo.value.messageList.findIndex(
        (item) => item._id === state.currentMessageInfo._id
      )
      const newUserInfo = { ...userInfo.value }
      newUserInfo.messageList.splice(mesIndex, 1)
      //  当前分页显示的数据
      state.currentPageListData = state.pageListData.slice(
        (state.currentPageNum - 1) * state.pageMaxskip,
        (state.currentPageNum - 1) * state.pageMaxskip + state.pageMaxskip
      )
      store.commit('setUserInfo', newUserInfo)

      // 返回消息列表
      isShowMes.value = false
    })
    .catch(() => {
      console.log()
    })
}

// 加入或移除星标信息
const changeStartMes = async (item: UserInfoMessageListTypes) => {
  const mesIndex = userInfo.value.messageList.findIndex(
    (mes) => mes._id === item._id
  )
  const { data } = await admintorStartMes(
    userInfo.value._id,
    item._id,
    mesIndex
  )
  if (data.code)
    return ElMessage({
      type: 'warning',
      message: data.mes
    })
  // 本地缓存 节约性能
  // 添加或移除星标
  // const localUserInfo = { ...userInfo.value }
  // localUserInfo.messageList[mesIndex].ifMark =
  //   !localUserInfo.messageList[mesIndex].ifMark
  // // 添加消息
  // if (item.ifMark) {
  //   localUserInfo.startUnread++
  //   localUserInfo.messageList[mesIndex].type = 3
  //   localUserInfo.messageList[mesIndex].ifStartRead = false
  // } else {
  //   localUserInfo.messageList[mesIndex].type =
  //     localUserInfo.messageList[mesIndex].constType
  // }
  // store.commit('setUserInfo', localUserInfo)
  admintorCheck().then(({ data }) => {
    if (data.code) {
      ElMessage({
        type: 'warning',
        message: data.mes
      })
      // 清除vuex和token
      cache.removeItem('token', CacheType.session)
      store.commit('clearUserInfo')
      return router.replace('/login')
    }
    // console.log(data.data?.vuexData.messageList.reverse())
    const newVuex = { ...data.data?.vuexData }
    newVuex.messageList?.reverse()
    // 更新vuex
    store.commit('setUserInfo', newVuex)
    // 更新token
    cache.setItem('token', data.data?.token, CacheType.session)
  })
  ElMessage({
    type: 'success',
    message: data.mes
  })
}

// 分页上一页下一页切换
const pageChangeSwitch: (bol?: boolean) => void = (bol = true) => {
  bol
    ? (state.currentPageNum = Math.min(++state.currentPageNum, state.pageNum))
    : (state.currentPageNum = Math.max(--state.currentPageNum, 1))
  state.currentPageListData = state.pageListData.slice(
    (state.currentPageNum - 1) * state.pageMaxskip,
    (state.currentPageNum - 1) * state.pageMaxskip + state.pageMaxskip
  )
}
</script>

<style scoped lang="less">
#mesageList {
  // 消息列表
  .message {
    margin-top: 20px;
    padding-bottom: 10px;
    display: flex;
    flex-direction: column;
    min-height: 272px;
    box-sizing: border-box;
    justify-content: space-between;
    // 空展示
    .empty {
      width: 200px;
      height: 200px;
      display: flex;
      margin: 0 auto;
      flex-direction: column;
      align-items: center;
      justify-content: space-around;
      color: #828690;
      i {
        font-size: 100px;
      }
      span {
        font-size: 14px;
      }
    }
    // 消息列表
    .meslist {
      .mes {
        height: 43.75px;
        display: flex;
        color: #828690;
        font-size: 12.5px;
        line-height: 43.75px;
        box-sizing: border-box;
        padding: 0 10px;
        position: relative;
        // 未读提示
        .pointer {
          position: relative;
          width: 13px;
          i {
            color: #f56c6c;
            font-size: 10px;
            position: absolute;
            top: -6px;
          }
        }
        &:hover {
          background-color: #f0f2f3;
          // background-color: rgba(240, 242, 243, 0.1);
          // background-color: rgba(51, 53, 67, 0.4);
        }
        .start {
          cursor: pointer;
          .active {
            color: #f4ea2a;
          }
          margin-right: 10px;
        }
        .tit {
          white-space: nowrap;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #828690;
        }
        .time {
          margin-left: 20px;
        }
      }
    }
    // 分页
    .pagination {
      display: flex;
      margin-top: 16px;
      margin-left: 12px;
      // 左右导航
      .pagePublic {
        width: 26px;
        height: 26px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(245, 108, 108, 0.3);
        border-radius: 50%;
        color: #f56c6c;
        cursor: pointer;
        i {
          font-size: 12px;
        }
        &:hover {
          color: #fff;
          background-color: #f56c6c;
        }
      }
      // 导航列表
      .pagelist {
        display: flex;
        align-items: center;
        margin: 0 10px;
        .pageitem {
          color: #f56c6c;
          margin: 0 6px;
          font-size: 12px;
          cursor: pointer;
          width: 26px;
          height: 26px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 50%;
          overflow: hidden;
          &:hover {
            background-color: #f56c6c;
            color: #fff;
          }
          &.active {
            background-color: #f56c6c;
            color: #fff;
          }
        }
      }
    }
  }
  // 显示具体的消息
  .showMes {
    margin-top: 20px;
    // 消息内容
    .title {
      padding-bottom: 15px;
      border-bottom: 1px solid #dfe1e3;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .centent {
        .tit {
          color: #f56c6c;
          font-size: 15px;
          font-weight: bold;
          word-spacing: 2px;
        }
        .time {
          font-size: 12px;
          margin-top: 10px;
          color: #969ba0;
        }
      }
      .more {
        display: flex;
        div {
          width: 40px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: rgba(245, 108, 108, 0.3);
          margin-right: 10px;
          border-radius: 16px;
          cursor: pointer;
          &:hover {
            background-color: #f56c6c;
            i {
              color: #fff;
            }
          }
          i {
            color: #f56c6c;
            &.active {
              color: #f4ea2a;
            }
          }
        }
      }
    }
    // 消息内容
    .des {
      margin-top: 10px;
      color: #969ba0;
      font-size: 14px;
      line-height: 2;
      white-space: wrap;
    }
  }
}
</style>
